import { defineStore } from "pinia";
import { Ref, ref } from "vue";
import { categoryParams } from "@/views/product/attribute/interface/interface.ts";
import { addOrUpdateAttributeAPI, deleteAttributeAPI, fetchAttributeAPI } from "@/api/product/attributeApi/attribute.ts";
import { attribute } from "@/api/product/attributeApi/interface.ts";

const useAttributeStore = defineStore("attributeStore", () => {
  /* 属性列表 */
  const attributeList: Ref<attribute[]> = ref<attribute[]>([]);
  /*screen是场景(0就是展示所有的属性列表的结构，1就是展示添加或者编辑某个属性的结构) */
  const screen: Ref<number> = ref<number>(0);
  /* 当前项的attribute */
  const currentAttribute: Ref<attribute> = ref<attribute>({});
  /* 添加属性状态还是编辑属性状态(默认为添加状态) */
  const edit: Ref<boolean> = ref<boolean>(false);

  /* 用于切换场景的回调函数(展示属性列表或添加者编辑) */
  const changeScreen: (value: number) => void = (value: number): void => {
    screen.value = value;
  };
  /* 发送请求获取属性列表的回调函数 */
  const fetchAttributeList: (categoryId: categoryParams) => Promise<void> = async (categoryId: categoryParams): Promise<void> => {
    const { data }: { data: attribute[] } = await fetchAttributeAPI(categoryId);
    attributeList.value = data;
  };
  /* 发送请求删除属性的回调函数 */
  const deleteAttribute: (attributeId: number) => Promise<string> = async (attributeId: number): Promise<string> => {
    await deleteAttributeAPI(attributeId);
    return "删除属性成功";
  };
  /* 发送请求添加属性或者修改属性的回调函数 */
  const addOrUpdateAttribute: (attr: attribute) => Promise<string> = async (attr: attribute): Promise<string> => {
    await addOrUpdateAttributeAPI(attr);
    return attr.id ? "修改属性成功" : "添加属性成功";
  };
  /* 获取点击编辑按钮的那一行的attribute  */
  const findCurrentAttribute: (attr: attribute) => void = (attr: attribute): void => {
    currentAttribute.value = attr;
  };
  const changeEdit: (flag: boolean) => void = (flag): void => {
    edit.value = flag;
  };
  return {
    attributeList,
    screen,
    currentAttribute,
    edit,
    fetchAttributeList,
    deleteAttribute,
    changeScreen,
    addOrUpdateAttribute,
    findCurrentAttribute,
    changeEdit,
  };
});

export default useAttributeStore;
